package crp.core.security.domain.repositories;

import com.qwlabs.lang.C2;
import com.qwlabs.lang.S2;
import com.qwlabs.panache.Where;
import crp.core.security.domain.models.RoleEntity;
import crp.core.security.domain.models.RoleQuery;
import io.quarkus.hibernate.orm.panache.PanacheQuery;
import io.quarkus.hibernate.orm.panache.PanacheRepositoryBase;
import io.quarkus.panache.common.Parameters;

import javax.enterprise.context.ApplicationScoped;
import java.util.Collection;
import java.util.Objects;
import java.util.stream.Stream;

@ApplicationScoped
public class RoleRepository implements PanacheRepositoryBase<RoleEntity, String> {

    public Stream<RoleEntity> findByIds(Collection<String> ids) {
        if (C2.isEmpty(ids)) {
            return Stream.empty();
        }
        return find("id in (:ids)", Parameters.with("ids", ids)).stream();
    }

    public PanacheQuery<RoleEntity> by(RoleQuery query) {
        Where where = Where.create();
        if (S2.isNotBlank(query.getKeyword())) {
            where.and("name like :keyword", "keyword", query.getKeyword() + "%");
        }
        if (Objects.nonNull(query.getTypes())) {
            where.and("type in (:types)", "types", query.getTypes());
        }
        return find(where.get(), where.getParameters());
    }
}
